package com.zpz.framework.zpzoauth.common.utils;

import com.alibaba.fastjson.JSON;
import com.zpz.framework.zpzoauth.common.redis.ZpzOauthRedisService;
import com.zpz.framework.zpzoauth.dao.ZpzOauthOauthClientDetailsMapper;
import com.zpz.framework.zpzoauth.pojo.po.OauthClientDetails;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * @author zhangpanzhi
 * @time 2019-07-09
 * @description 未经本人允许请勿随便改动，尊重劳动
 * */
@Component
public class ZpzOauthRequestUtil {
    @Resource
    private ZpzOauthRedisService zpzOauthRedisService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private ZpzOauthOauthClientDetailsMapper zpzOauthOauthClientDetailsMapper;
    public static String APPLICATION_NAME;

    @Value("${zpzOauth.redis.pre}")
    public void setApplicationName(String applicationName){
        APPLICATION_NAME=applicationName;
    }
    public  OauthClientDetails getClient(String clientId){
        String key= APPLICATION_NAME+"_"+ ZpzOauthCommonConstant.CLIENT_INFO+":basic:"+clientId;
        String _client = zpzOauthRedisService.get(key);
        OauthClientDetails client=null;
        if (!StringUtils.isNotBlank(_client)){
            OauthClientDetails oc = new OauthClientDetails();
            oc.setClientId(clientId);
            oc.setDelFlag(0);
            List<OauthClientDetails> cs = zpzOauthOauthClientDetailsMapper.select(oc);
            if (cs==null||cs.size()<=0){
//                throw new OAuth2Exception("无效的客户端：查无此客户端信息");
                return null;
            }
            client=cs.get(0);
            zpzOauthRedisService.set(key, JSON.toJSONString(client));
            redisTemplate.expire(key, ZpzOauthCommonConstant.RELEASE_ACCESS_HOURS, TimeUnit.HOURS);

        }else{
            try {
                client=JSON.parseObject(_client,OauthClientDetails.class);
            } catch (Exception e) {
//                return null;
//                throw new OAuth2Exception("无效的客户端："+e.getMessage());
            }
        }
        return client;
    }
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    public static Map<String,String> getLicense(HttpServletRequest request){
        String lience = request.getHeader(ZpzOauthCommonConstant.REQUEST_HEADER_LIENCE);
        String clientId=null;
        String apicode=null;
        String ucode=null;
        try {
            if (StringUtils.isNotBlank(lience)){
                String _license = new String(Base64.decodeBase64(lience));
                String[] liencese = _license.split(":");
                clientId=liencese[0];
                apicode=liencese[1];
                ucode=liencese[2];
                Map<String,String> re=new HashMap<>();
                re.put("clientId",clientId);
                re.put("apicode",apicode);
                re.put("ucode",ucode);
                return re;
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}
